package com.shiguiwu.springmybatis.javabase.optional;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.shiguiwu.springmybatis.util.Car;
import com.shiguiwu.springmybatis.util.Person;
import javafx.print.Collation;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: stone
 * @date: Created by 2022/9/2 21:32
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.optional
 */
@Slf4j
public class OptionalTests {

    public static void main(String[] args) {
        //testOptionalIsNull();

        //testOptionalColl();
        testStringThrow();
    }


    public static void testOptionalIsNull() {
        Person person = new Person();
        person.setAge(1);

        String integer = Optional.ofNullable(person).map(e -> {
            System.out.println(e.getAge());
            double v = e.getAge().doubleValue();
            //todo map里面出现异常会怎么样？ map 里面如果是bull ，那就是报会空指针
            return String.valueOf(e.getAge());
        }).orElse("1");

        log.info("是否空指针 ===> {}", integer);


        //但是如果转换元素里是空，是不会爆异常的
        String anElse = Optional.of(person)
                .map(Person::getCar)
                .map(Car::getCarName)
                .orElse("1");

        log.info("map 中有空的 ===> {}", anElse);

    }


    /**
     * 集合和他使用
     */
    public static void testOptionalColl() {
        //1，一种是必须不为空集合那就是操作数据库了,一定要有值的场景

        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);

        Optional.ofNullable(list1)
                .filter(l -> !CollUtil.isEmpty(list1))
                .ifPresent(lx -> log.info("操作数据库 ===> {}", JSONUtil.toJsonStr(lx)));


        //2。可以为空集合，只是为了变量，这个是便利或者是读的

        List<Integer> list = new ArrayList<>();

        List<String> collect = Optional.of(list).orElse(new ArrayList<>())
                .stream()
                .map(String::valueOf)
                .collect(Collectors.toList());


        log.info("hahah ===> {}", JSONUtil.toJsonStr(collect));

    }


    public static void testCollThrow() {
        //1,list是null 报错
        //2，list 空集合也报错
        //3，list 是1 也是报错
        //4，list 是2
        List<String> list = null;
        //List<String> list = new ArrayList<>();
        //list.add("1");
        //list.add("2");
        Optional.ofNullable(list).filter(x -> x.size() == 1).orElseThrow(() -> new RuntimeException("断言是false"));

    }


    public static void testStringThrow() {
        String a = "  ";
        Optional.ofNullable(a).filter(StrUtil::isNotBlank).orElseThrow(() -> new RuntimeException("断言是false"));

    }
}
